#include <iostream>
#include <memory>

using std::cout;
using std::endl;
using std::shared_ptr;

class Point
{
public:
    Point(int ix = 0, int iy = 0)
    : _ix(ix)
    , _iy(iy)
    {
        cout << "Point(int = 0, int = 0)" << endl;
    }

    void print() const
    {
        cout << "(" << _ix 
             << ", " << _iy
             << ")" << endl;
    }

    ~Point()
    {
        cout << "~Point()" << endl;
    }
private:
    int _ix;
    int _iy;
};

void test()
{
    //问题的本质：使用了不同的智能指针托管同一块堆空间
    Point *pt = new Point(1, 2);
    shared_ptr<Point> sp(pt);
    /* shared_ptr<Point> sp2(pt); */
    shared_ptr<Point> sp2 = sp;
    cout << "sp.use_count() = " << sp.use_count() << endl;
    cout << "sp2.use_count() = " << sp2.use_count() << endl;
}

void test2()
{
    //问题的本质：使用了不同的智能指针托管同一块堆空间
    shared_ptr<Point> sp(new Point(1, 2));
    cout << "sp = ";
    sp->print();
    cout << "sp.use_count() = " << sp.use_count() << endl;

    cout << endl;
    shared_ptr<Point> sp2(new Point(3, 4));
    cout << "sp2 = ";
    sp2->print();
    cout << "sp2.use_count() = " << sp2.use_count() << endl;

    cout << endl;
    sp.reset(sp2.get());
    cout << "sp = ";
    sp->print();
    cout << "sp2 = ";
    sp2->print();
    cout << "sp.use_count() = " << sp.use_count() << endl;
    cout << "sp2.use_count() = " << sp2.use_count() << endl;
}

int main(int argc, char *argv[])
{
    test2();
    return 0;
}

